package com.qf.dao.impl;

import com.qf.dao.UserDao;
import com.qf.pojo.User;
import com.qf.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
public class UserDaoImpl implements UserDao {

    @Override
    public long selectCountByUsername(String username) {
        QueryRunner qf = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select count(0) from tb_user where username = ? and role=0";
        try {
            Long count = (Long) qf.query(sql, new ScalarHandler(), username);
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("检查用户名是否存在失败!!!");
        }
        return 0;
    }

    @Override
    public int insert(User user) {
        QueryRunner qf = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "insert into tb_user values(null ,?,md5(?),?,?,?,?,?)";
        try {
            int count = qf.update(sql, user.getUsername(),
                    user.getPassword(), user.getEmail(), user.getGender(), user.getFlag(), 1, "");
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("注册用户失败!!!");
        }
        return  0;

    }

    @Override
    public User selectByUsernameAndPassword(String username, String password) {
        QueryRunner qf = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select id,username,password,email,gender,flag,role,code from tb_user where username = ? and password= md5(?) and role=1";
        try {
            User user = qf.query(sql, new BeanHandler<>(User.class), username, password);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("检查用户名是否存在失败!!!");
        }
        return null;
    }
}
